﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EntityBinder.Interface;

namespace EntityBinder.Transformer
{
	public abstract class AbstractTransformer<T> : ITransformer
	{
		public delegate bool TryParseDelegate(string _value, out T _parsed);

		private TryParseDelegate m_parseFunction;

		public AbstractTransformer()
		{
			m_parseFunction = null;
		}

		public AbstractTransformer(TryParseDelegate _function)
		{
			m_parseFunction = _function;
		}

		public virtual object Read(string _value)
		{
			T result;
			if(m_parseFunction(_value, out result))
			{
				return result;
			}
			
			throw new EntityBinderException("AbstractParseTransformer<" + typeof(T) + ">", "Read", "Can not convert string \"" + _value + "\" to a " + typeof(T) + " object");
		}

		public virtual string Write(object _data)
		{
			if(_data is T)
			{
				return ((T)_data).ToString();
			}

			throw new EntityBinderException("AbstractParseTransformer<" + typeof(T) + ">", "Write", "Can not convert object of type " + _data.GetType() + " to " + typeof(T) + " to perform the transformation");
		}
	}
}
